<template>
  <div class="app-container">
    <div class="div-sch">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="策略名" prop="strategyName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入策略名"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="通行标签" prop="accessTag">
          <el-select clearable v-model="queryParams.accessTag" placeholder="可多选"  collapse-tags multiple >
            <el-option 
              v-for="item in tagList" 
              :key="item.index"
              :value="item.tagId"
              :label="item.tagName"
              ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通行设备" prop="accessDevice">
          <el-select clearable v-model="queryParams.accessDevice" placeholder="可多选"  collapse-tags multiple >
            <el-option 
              v-for="item in deviceList" 
              :key="item.index"
              :value="item.deviceId"
              :label="item.deviceName"
              ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="div-t">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:user:add']"
          >新增策略</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleBatchDelete"
            v-hasPermi="['monitor:operlog:remove']"
          >批量删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table ref="tables"  border v-loading="loading"   :data="list" @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="策略名"  align="center" prop="strategyName" />
        <el-table-column label="所属公司"  align="center" prop="deptName" />
        <el-table-column label="通行时段"  align="center" prop="accessTime" >
          <template slot-scope="scope">
            {{setAccessTime(scope.row)}}
          </template>
        </el-table-column>
        <el-table-column label="标签" align="center" prop="tagNames">
          <template slot-scope="scope">
            <el-tag 
              v-for="item in setTag(scope.row)"
              :key="item.index"
              size="mini" 
            >{{item}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="启用禁用" align="center" prop="isOn">
          <template slot-scope="scope">
            <el-switch
              class="switchStyle"       
              v-model="scope.row.isOn" 
              active-text="ON"          
              inactive-text="OFF"  
              @change="changeOn(scope.row)"     
              active-color="#2d8cf0"    
              inactive-color="#ccc">  
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['monitor:operlog:query']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              style="color:red"
              @click="handleDelete(scope.row)"
              v-hasPermi="['monitor:operlog:query']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改标签的对话框 -->
      <AddOrUpdate 
      ref="mychild"
      :title="saveModal.title" 
      :visible.sync="saveModal.open" 
       width="800px" 
      :isUpdate="saveModal.isUpdate"
      :updateData="saveModal.updateData"
      append-to-body/>
   
    </div>
  </div>
</template>
<script>
import { strategyApi } from "@/api/business/strategy";
import { deviceApi } from "@/api/business/device";
import { getTagAllList } from "@/api/business/tag";
import AddOrUpdate from "./strategy-add-update";
export default {
  name: "strategy",
  components: {AddOrUpdate},
  dicts: ['sys_oper_type', 'sys_common_status'],
  data() {
    return {
      tableHeight:0,
      // 遮罩层
      loading: true,
      // 下拉框数组
      deviceList: [],
      tagList: [],
      deleteParam:{
        ids: [],
        strategyIds:[]
      },
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 是否显示弹出层
      saveModal:{
        // 弹出层标题
        title: "",
        open: false,
        isUpdate: false,
        updateData: undefined,
      },
      // 日期范围
      dateRange: [],
      // 默认排序
      defaultSort: {prop: 'operTime', order: 'descending'},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        strategyName: undefined,
        accessTag: [],
        accessDevice: [],
      },
      // 表单校验
      rules: {
        tagName: [
          { required: true, message: "标签名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.init();
  },
  methods: {
    getTableHeight(){
      this.tableHeight = window.innerHeight - 300;
    },
    init(){
      this.getList();
      this.getTableHeight();
      deviceApi
      .getDeviceAllList()
      .then(res => {
        this.deviceList = res.data;
      })
      .catch(error => {
        console.log(error);
      });
      getTagAllList()
        .then(res => {
          this.tagList = res.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    setAccessTime(row){
      if(row.accessRule!="all"){
        const accessTimeArr = JSON.parse(row.accessTime);
        return accessTimeArr[0] + " ~ " + accessTimeArr[1] ;
      }else{
        return "全时段";
      }
    },
    setTag(row){
      if(row.tagNames!=null){
        const tagNames = JSON.parse(JSON.stringify(row.tagNames)).split(',');
        return tagNames;
      }else{
        return [];
      }
    },
    /** 查询 */
    getList() {
      this.loading = true;
      strategyApi.getStrategyList(this.queryParams).then( res => {
          this.list = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        }
      ).catch(err=>{
        this.loading = false;
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order)
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.deleteParam.ids = selection.map(item => item.id)
      this.deleteParam.strategyIds = selection.map(item => item.strategyId)
      this.multiple = !selection.length
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.saveModal.title = "添加策略";
      this.saveModal.isUpdate = false;
      this.saveModal.updateData= undefined;
      this.saveModal.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.$refs.mychild.setTagAndDevice(row.strategyId);
      this.saveModal.title = "修改策略";
      this.saveModal.isUpdate = true;
      this.saveModal.updateData = this.deepClone(row);
      this.saveModal.open = true;
      
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除？','提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res=>{
         strategyApi.deleteStrategyById({ id: row.id, strategyId: row.strategyId })
          .then(res=>{
            this.getList();
            this.$message.success('删除成功!');
          })
          .catch(error=>{
            console.error(error);
          })
        });  
  },
  handleBatchDelete(){
    this.$confirm('是否确认删除？','提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res=>{
         strategyApi
          .deleteBatchStrategy({
            ids: this.deleteParam.ids,
            strategyIds: this.deleteParam.strategyIds
          })
          .then(res => {
            this.$message.success("刪除成功");
            this.getList();
          })
          .catch(error => {
            console.log(error);
          });
        });  
  },
    // 表单重置
    reset() {
      this.form = {};
    },
    // 取消按钮
    cancel() {
      this.saveModal.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm: function() {
      // this.$refs["form"].validate(valid => {
      //   if (valid) {
      //     if (this.form.id != undefined) {
      //       updateTag(this.form).then(response => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addTag(this.form).then(response => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
     changeOn(row){
      strategyApi.changeOn({isOn:row.isOn,deviceId:row.deviceId})
        .then(res=>{
           this.$message.success('执行成功!');
        })
        .catch(error=>{
          console.error(error);
        })
    },
  }
};
</script>
<style  >
.div-t {
  background: white;
  padding: 10px 10px 20px 10px;
  border-radius: 5px;
  /* border: 1px solid rgb(211, 208, 208); */
}
.div-sch {
  background: white;
  padding: 10px 10px 0px 10px;
  border-radius: 5px;
  margin-bottom: 10px;
}
.switchStyle .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
  }
 .el-switch__core{
    background-color: rgba(166, 166, 166, 1) ;
  }
  .switchStyle .el-switch__label--left {
    z-index: 9;
    left: 8px;
  }
  .switchStyle .el-switch__label--right {
    z-index: 9;
    left: -15px;
  }
  .switchStyle .el-switch__label.is-active {
    display: block;
  }
  .switchStyle.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 60px !important;
  }
</style>